package control;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import au.com.bytecode.opencsv.CSVReader;


public class SudokuReader {
	
	File dir = new File(model.Data.PFADZUSUDOKUORDNER);
	
	File file;
	
	public SudokuReader(String filePath) {
		file = new File(filePath);
		pruefeObDateiVorhanden();
	}
	
	public void pruefeObDateiVorhanden() {
		if (file.exists() == true) {
		}
		else {
			try {
				if (dir.exists() == false) {
					dir.mkdirs();
				}
				file.createNewFile();
				if (file.exists() != true) {
				}
			}
			catch (IOException exception) {
				System.err.println(exception.getMessage());
			}
		}
	}
	
	public void loadAllSudokus() {
		try (CSVReader reader = new CSVReader(new FileReader(file))) {
			List<String[]> sudokuList = reader.readAll();
			System.out.println(sudokuList);
		}
		catch (IOException exception) {
			System.err.println(exception.getMessage());
		}
	}
	
	public byte[][] loadSudoku() {
		byte[][] byteFeld = new byte[9][9];
		try (CSVReader reader = new CSVReader(new FileReader(file))) {
			String[] sBuffer = new String[1];
			int sBufferZaehler=0;
			sBuffer=reader.readNext();
			for (int i=0; i<9; i++) {
				for (int j=0; j<9; j++) {
					byteFeld[i][j]=Byte.parseByte(sBuffer[0].substring(sBufferZaehler));
				}
			}
			return byteFeld;
		}
		catch (IOException exception) {
			System.err.println(exception.getMessage());
			return null;
		}
	}
	
	public boolean sudokuSchonVorhanden(byte[][] sudokuFeld) {
		byte[][] byteFeld = new byte[9][9];
		try (CSVReader reader = new CSVReader(new FileReader(file))) {
			String[] sBuffer;
			int sBufferZaehler=0;
			while ((sBuffer = reader.readNext()) != null) {
				sBufferZaehler=0;
				for (int i=0; i<9; i++) {
					for (int j=0; j<9; j++) {
						byteFeld[i][j]=Byte.parseByte(sBuffer[sBufferZaehler]);
						sBufferZaehler++;
					}
				}
				if (Arrays.deepEquals(byteFeld, sudokuFeld) == true) {
					return true;
				}
			}
			return false;
		}
		catch (IOException exception) {
			System.err.println(exception.getMessage());
			return false;
		}
	}

}
